home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 22 / CU Amiga Magazine's Super CD-ROM 22 (1998)(EMAP Images)(GB)[!][issue 1998-05].iso / PowerPC / Archivers / ZLib / trees.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-02-20  |  39.8 KB  |  1,097 lines

  1. /* trees.c -- output deflated data using Huffman coding
  2.  * Copyright (C) 1995-1996 Jean-loup Gailly
  3.  * For conditions of distribution and use, see copyright notice in zlib.h 
  4.  */
  5.  
  6. /*
  7.  *  ALGORITHM
  8.  *
  9.  *      The "deflation" process uses several Huffman trees. The more
  10.  *      common source values are represented by shorter bit sequences.
  11.  *
  12.  *      Each code tree is stored in a compressed form which is itself
  13.  * a Huffman encoding of the lengths of all the code strings (in
  14.  * ascending order by source values).  The actual code strings are
  15.  * reconstructed from the lengths in the inflate process, as described
  16.  * in the deflate specification.
  17.  *
  18.  *  REFERENCES
  19.  *
  20.  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  21.  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  22.  *
  23.  *      Storer, James A.
  24.  *          Data Compression:  Methods and Theory, pp. 49-50.
  25.  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  26.  *
  27.  *      Sedgewick, R.
  28.  *          Algorithms, p290.
  29.  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  30.  */
  31.  
  32. /* $Id: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */
  33.  
  34. #include "deflate.h"
  35.  
  36. #ifdef DEBUG
  37. #  include <ctype.h>
  38. #endif
  39.  
  40. /* ===========================================================================
  41.  * Constants
  42.  */
  43.  
  44. #define MAX_BL_BITS 7
  45. /* Bit length codes must not exceed MAX_BL_BITS bits */
  46.  
  47. #define END_BLOCK 256
  48. /* end of block literal code */
  49.  
  50. #define REP_3_6      16
  51. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  52.  
  53. #define REPZ_3_10    17
  54. /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  55.  
  56. #define REPZ_11_138  18
  57. /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  58.  
  59. local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  60.    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  61.  
  62. local int extra_dbits[D_CODES] /* extra bits for each distance code */
  63.    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  64.  
  65. local int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  66.    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  67.  
  68. local uch bl_order[BL_CODES]
  69.    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  70. /* The lengths of the bit length codes are sent in order of decreasing
  71.  * probability, to avoid transmitting the lengths for unused bit length codes.
  72.  */
  73.  
  74. #define Buf_size (8 * 2*sizeof(char))
  75. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  76.  * more than 16 bits on some systems.)
  77.  */
  78.  
  79. /* ===========================================================================
  80.  * Local data. These are initialized only once.
  81.  */
  82.  
  83. local ct_data static_ltree[L_CODES+2];
  84. /* The static literal tree. Since the bit lengths are imposed, there is no
  85.  * need for the L_CODES extra codes used during heap construction. However
  86.  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  87.  * below).
  88.  */
  89.  
  90. local ct_data static_dtree[D_CODES];
  91. /* The static distance tree. (Actually a trivial tree since all codes use
  92.  * 5 bits.)
  93.  */
  94.  
  95. local uch dist_code[512];
  96. /* distance codes. The first 256 values correspond to the distances
  97.  * 3 .. 258, the last 256 values correspond to the top 8 bits of
  98.  * the 15 bit distances.
  99.  */
  100.  
  101. local uch length_code[MAX_MATCH-MIN_MATCH+1];
  102. /* length code for each normalized match length (0 == MIN_MATCH) */
  103.  
  104. local int base_length[LENGTH_CODES];
  105. /* First normalized length for each code (0 = MIN_MATCH) */
  106.  
  107. local int base_dist[D_CODES];
  108. /* First normalized distance for each code (0 = distance of 1) */
  109.  
  110. struct static_tree_desc_s {
  111.     ct_data *static_tree;        /* static tree or NULL */
  112.     intf    *extra_bits;         /* extra bits for each code or NULL */
  113.     int     extra_base;          /* base index for extra_bits */
  114.     int     elems;               /* max number of elements in the tree */
  115.     int     max_length;          /* max bit length for the codes */
  116. };
  117.  
  118. local static_tree_desc  static_l_desc =
  119. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  120.  
  121. local static_tree_desc  static_d_desc =
  122. {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
  123.  
  124. local static_tree_desc  static_bl_desc =
  125. {(ct_data *)0, extra_blbits, 0,      BL_CODES, MAX_BL_BITS};
  126.  
  127. /* ===========================================================================
  128.  * Local (static) routines in this file.
  129.  */
  130.  
  131. local void tr_static_init OF((void));
  132. local void init_block     OF((deflate_state *s));
  133. local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
  134. local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
  135. local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
  136. local void build_tree     OF((deflate_state *s, tree_desc *desc));
  137. local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  138. local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  139. local int  build_bl_tree  OF((deflate_state *s));
  140. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  141.                               int blcodes));
  142. local void compress_block OF((deflate_state *s, ct_data *ltree,
  143.                               ct_data *dtree));
  144. local void set_data_type  OF((deflate_state *s));
  145. local unsigned bi_reverse OF((unsigned value, int length));
  146. local void bi_windup      OF((deflate_state *s));
  147. local void bi_flush       OF((deflate_state *s));
  148. local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
  149.                               int header));
  150.  
  151. #ifndef DEBUG
  152. #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  153.    /* Send a code of the given tree. c and tree must not have side effects */
  154.  
  155. #else /* DEBUG */
  156. #  define send_code(s, c, tree) \
  157.      { if (verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  158.        send_bits(s, tree[c].Code, tree[c].Len); }
  159. #endif
  160.  
  161. #define d_code(dist) \
  162.    ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  163. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  164.  * must not have side effects. dist_code[256] and dist_code[257] are never
  165.  * used.
  166.  */
  167.  
  168. /* ===========================================================================
  169.  * Output a short LSB first on the stream.
  170.  * IN assertion: there is enough room in pendingBuf.
  171.  */
  172. #define put_short(s, w) { \
  173.     put_byte(s, (uch)((w) & 0xff)); \
  174.     put_byte(s, (uch)((ush)(w) >> 8)); \
  175. }
  176.  
  177. /* ===========================================================================
  178.  * Send a value on a given number of bits.
  179.  * IN assertion: length <= 16 and value fits in length bits.
  180.  */
  181. #ifdef DEBUG
  182. local void send_bits      OF((deflate_state *s, int value, int length));
  183.  
  184. local void send_bits(s, value, length)
  185.     deflate_state *s;
  186.     int value;  /* value to send */
  187.     int length; /* number of bits */
  188. {
  189.     Tracevv((stderr," l %2d v %4x ", length, value));
  190.     Assert(length > 0 && length <= 15, "invalid length");
  191.     s->bits_sent += (ulg)length;
  192.  
  193.     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  194.      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  195.      * unused bits in value.
  196.      */
  197.     if (s->bi_valid > (int)Buf_size - length) {
  198.         s->bi_buf |= (value << s->bi_valid);
  199.         put_short(s, s->bi_buf);
  200.         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  201.         s->bi_valid += length - Buf_size;
  202.     } else {
  203.         s->bi_buf |= value << s->bi_valid;
  204.         s->bi_valid += length;
  205.     }
  206. }
  207. #else /* !DEBUG */
  208.  
  209. #define send_bits(s, value, length) \
  210. { int len = length;\
  211.   if (s->bi_valid > (int)Buf_size - len) {\
  212.     int val = value;\
  213.     s->bi_buf |= (val << s->bi_valid);\
  214.     put_short(s, s->bi_buf);\
  215.     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  216.     s->bi_valid += len - Buf_size;\
  217.   } else {\
  218.     s->bi_buf |= (value) << s->bi_valid;\
  219.     s->bi_valid += len;\
  220.   }\
  221. }
  222. #endif /* DEBUG */
  223.  
  224.  
  225. #define MAX(a,b) (a >= b ? a : b)
  226. /* the arguments must not have side effects */
  227.  
  228. /* ===========================================================================
  229.  * Initialize the various 'constant' tables. In a multi-threaded environment,
  230.  * this function may be called by two threads concurrently, but this is
  231.  * harmless since both invocations do exactly the same thing.
  232.  */
  233. local void tr_static_init()
  234. {
  235.     static int static_init_done = 0;
  236.     int n;        /* iterates over tree elements */
  237.     int bits;     /* bit counter */
  238.     int length;   /* length value */
  239.     int code;     /* code value */
  240.     int dist;     /* distance index */
  241.     ush bl_count[MAX_BITS+1];
  242.     /* number of codes at each bit length for an optimal tree */
  243.  
  244.     if (static_init_done) return;
  245.  
  246.     /* Initialize the mapping length (0..255) -> length code (0..28) */
  247.     length = 0;
  248.     for (code = 0; code < LENGTH_CODES-1; code++) {
  249.         base_length[code] = length;
  250.         for (n = 0; n < (1<<extra_lbits[code]); n++) {
  251.             length_code[length++] = (uch)code;
  252.         }
  253.     }
  254.     Assert (length == 256, "tr_static_init: length != 256");
  255.     /* Note that the length 255 (match length 258) can be represented
  256.      * in two different ways: code 284 + 5 bits or code 285, so we
  257.      * overwrite length_code[255] to use the best encoding:
  258.      */
  259.     length_code[length-1] = (uch)code;
  260.  
  261.     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  262.     dist = 0;
  263.     for (code = 0 ; code < 16; code++) {
  264.         base_dist[code] = dist;
  265.         for (n = 0; n < (1<<extra_dbits[code]); n++) {
  266.             dist_code[dist++] = (uch)code;
  267.         }
  268.     }
  269.     Assert (dist == 256, "tr_static_init: dist != 256");
  270.     dist >>= 7; /* from now on, all distances are divided by 128 */
  271.     for ( ; code < D_CODES; code++) {
  272.         base_dist[code] = dist << 7;
  273.         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  274.             dist_code[256 + dist++] = (uch)code;
  275.         }
  276.     }
  277.     Assert (dist == 256, "tr_static_init: 256+dist != 512");
  278.  
  279.     /* Construct the codes of the static literal tree */
  280.     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  281.     n = 0;
  282.     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  283.     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  284.     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  285.     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  286.     /* Codes 286 and 287 do not exist, but we must include them in the
  287.      * tree construction to get a canonical Huffman tree (longest code
  288.      * all ones)
  289.      */
  290.     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  291.  
  292.     /* The static distance tree is trivial: */
  293.     for (n = 0; n < D_CODES; n++) {
  294.         static_dtree[n].Len = 5;
  295.         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  296.     }
  297.     static_init_done = 1;
  298. }
  299.  
  300. /* ===========================================================================
  301.  * Initialize the tree data structures for a new zlib stream.
  302.  */
  303. void _tr_init(deflate_state *s)
  304. {
  305.     tr_static_init();
  306.  
  307.     s->compressed_len = 0L;
  308.  
  309.     s->l_desc.dyn_tree = s->dyn_ltree;
  310.     s->l_desc.stat_desc = &static_l_desc;
  311.  
  312.     s->d_desc.dyn_tree = s->dyn_dtree;
  313.     s->d_desc.stat_desc = &static_d_desc;
  314.  
  315.     s->bl_desc.dyn_tree = s->bl_tree;
  316.     s->bl_desc.stat_desc = &static_bl_desc;
  317.  
  318.     s->bi_buf = 0;
  319.     s->bi_valid = 0;
  320.     s->last_eob_len = 8; /* enough lookahead for inflate */
  321. #ifdef DEBUG
  322.     s->bits_sent = 0L;
  323. #endif
  324.  
  325.     /* Initialize the first block of the first file: */
  326.     init_block(s);
  327. }
  328.  
  329. /* ===========================================================================
  330.  * Initialize a new block.
  331.  */
  332. local void init_block(deflate_state *s)
  333. {
  334.     int n; /* iterates over tree elements */
  335.  
  336.     /* Initialize the trees. */
  337.     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
  338.     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
  339.     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  340.  
  341.     s->dyn_ltree[END_BLOCK].Freq = 1;
  342.     s->opt_len = s->static_len = 0L;
  343.     s->last_lit = s->matches = 0;
  344. }
  345.  
  346. #define SMALLEST 1
  347. /* Index within the heap array of least frequent node in the Huffman tree */
  348.  
  349.  
  350. /* ===========================================================================
  351.  * Remove the smallest element from the heap and recreate the heap with
  352.  * one less element. Updates heap and heap_len.
  353.  */
  354. #define pqremove(s, tree, top) \
  355. {\
  356.     top = s->heap[SMALLEST]; \
  357.     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  358.     pqdownheap(s, tree, SMALLEST); \
  359. }
  360.  
  361. /* ===========================================================================
  362.  * Compares to subtrees, using the tree depth as tie breaker when
  363.  * the subtrees have equal frequency. This minimizes the worst case length.
  364.  */
  365. #define smaller(tree, n, m, depth) \
  366.    (tree[n].Freq < tree[m].Freq || \
  367.    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  368.  
  369. /* ===========================================================================
  370.  * Restore the heap property by moving down the tree starting at node k,
  371.  * exchanging a node with the smallest of its two sons if necessary, stopping
  372.  * when the heap property is re-established (each father smaller than its
  373.  * two sons).
  374.  */
  375. local void pqdownheap(deflate_state *s, ct_data *tree, int k)
  376. {
  377.     int v = s->heap[k];
  378.     int j = k << 1;  /* left son of k */
  379.     while (j <= s->heap_len) {
  380.         /* Set j to the smallest of the two sons: */
  381.         if (j < s->heap_len &&
  382.             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  383.             j++;
  384.         }
  385.         /* Exit if v is smaller than both sons */
  386.         if (smaller(tree, v, s->heap[j], s->depth)) break;
  387.  
  388.         /* Exchange v with the smallest son */
  389.         s->heap[k] = s->heap[j];  k = j;
  390.  
  391.         /* And continue down the tree, setting j to the left son of k */
  392.         j <<= 1;
  393.     }
  394.     s->heap[k] = v;
  395. }
  396.  
  397. /* ===========================================================================
  398.  * Compute the optimal bit lengths for a tree and update the total bit length
  399.  * for the current block.
  400.  * IN assertion: the fields freq and dad are set, heap[heap_max] and
  401.  *    above are the tree nodes sorted by increasing frequency.
  402.  * OUT assertions: the field len is set to the optimal bit length, the
  403.  *     array bl_count contains the frequencies for each bit length.
  404.  *     The length opt_len is updated; static_len is also updated if stree is
  405.  *     not null.
  406.  */
  407. local void gen_bitlen(deflate_state *s, tree_desc *desc)
  408. {
  409.     ct_data *tree  = desc->dyn_tree;
  410.     int max_code   = desc->max_code;
  411.     ct_data *stree = desc->stat_desc->static_tree;
  412.     intf *extra    = desc->stat_desc->extra_bits;
  413.     int base       = desc->stat_desc->extra_base;
  414.     int max_length = desc->stat_desc->max_length;
  415.     int h;              /* heap index */
  416.     int n, m;           /* iterate over the tree elements */
  417.     int bits;           /* bit length */
  418.     int xbits;          /* extra bits */
  419.     ush f;              /* frequency */
  420.     int overflow = 0;   /* number of elements with bit length too large */
  421.  
  422.     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  423.  
  424.     /* In a first pass, compute the optimal bit lengths (which may
  425.      * overflow in the case of the bit length tree).
  426.      */
  427.     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  428.  
  429.     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  430.         n = s->heap[h];
  431.         bits = tree[tree[n].Dad].Len + 1;
  432.         if (bits > max_length) bits = max_length, overflow++;
  433.         tree[n].Len = (ush)bits;
  434.         /* We overwrite tree[n].Dad which is no longer needed */
  435.  
  436.         if (n > max_code) continue; /* not a leaf node */
  437.  
  438.         s->bl_count[bits]++;
  439.         xbits = 0;
  440.         if (n >= base) xbits = extra[n-base];
  441.         f = tree[n].Freq;
  442.         s->opt_len += (ulg)f * (bits + xbits);
  443.         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  444.     }
  445.     if (overflow == 0) return;
  446.  
  447.     Trace((stderr,"\nbit length overflow\n"));
  448.     /* This happens for example on obj2 and pic of the Calgary corpus */
  449.  
  450.     /* Find the first bit length which could increase: */
  451.     do {
  452.         bits = max_length-1;
  453.         while (s->bl_count[bits] == 0) bits--;
  454.         s->bl_count[bits]--;      /* move one leaf down the tree */
  455.         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  456.         s->bl_count[max_length]--;
  457.         /* The brother of the overflow item also moves one step up,
  458.          * but this does not affect bl_count[max_length]
  459.          */
  460.         overflow -= 2;
  461.     } while (overflow > 0);
  462.  
  463.     /* Now recompute all bit lengths, scanning in increasing frequency.
  464.      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  465.      * lengths instead of fixing only the wrong ones. This idea is taken
  466.      * from 'ar' written by Haruhiko Okumura.)
  467.      */
  468.     for (bits = max_length; bits != 0; bits--) {
  469.         n = s->bl_count[bits];
  470.         while (n != 0) {
  471.             m = s->heap[--h];
  472.             if (m > max_code) continue;
  473.             if (tree[m].Len != (unsigned) bits) {
  474.                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  475.                 s->opt_len += ((long)bits - (long)tree[m].Len)
  476.                               *(long)tree[m].Freq;
  477.                 tree[m].Len = (ush)bits;
  478.             }
  479.             n--;
  480.         }
  481.     }
  482. }
  483.  
  484. /* ===========================================================================
  485.  * Generate the codes for a given tree and bit counts (which need not be
  486.  * optimal).
  487.  * IN assertion: the array bl_count contains the bit length statistics for
  488.  * the given tree and the field len is set for all tree elements.
  489.  * OUT assertion: the field code is set for all tree elements of non
  490.  *     zero code length.
  491.  */
  492. local void gen_codes (ct_data *tree, int max_code, ushf *bl_count)
  493. {
  494.     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  495.     ush code = 0;              /* running code value */
  496.     int bits;                  /* bit index */
  497.     int n;                     /* code index */
  498.  
  499.     /* The distribution counts are first used to generate the code values
  500.      * without bit reversal.
  501.      */
  502.     for (bits = 1; bits <= MAX_BITS; bits++) {
  503.         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  504.     }
  505.     /* Check that the bit counts in bl_count are consistent. The last code
  506.      * must be all ones.
  507.      */
  508.     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  509.             "inconsistent bit counts");
  510.     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  511.  
  512.     for (n = 0;  n <= max_code; n++) {
  513.         int len = tree[n].Len;
  514.         if (len == 0) continue;
  515.         /* Now reverse the bits */
  516.         tree[n].Code = bi_reverse(next_code[len]++, len);
  517.  
  518.         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  519.              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  520.     }
  521. }
  522.  
  523. /* ===========================================================================
  524.  * Construct one Huffman tree and assigns the code bit strings and lengths.
  525.  * Update the total bit length for the current block.
  526.  * IN assertion: the field freq is set for all tree elements.
  527.  * OUT assertions: the fields len and code are set to the optimal bit length
  528.  *     and corresponding code. The length opt_len is updated; static_len is
  529.  *     also updated if stree is not null. The field max_code is set.
  530.  */
  531. local void build_tree(deflate_state *s, tree_desc *desc)
  532. {
  533.     ct_data *tree   = desc->dyn_tree;
  534.     ct_data *stree  = desc->stat_desc->static_tree;
  535.     int elems       = desc->stat_desc->elems;
  536.     int n, m;          /* iterate over heap elements */
  537.     int max_code = -1; /* largest code with non zero frequency */
  538.     int node;          /* new node being created */
  539.  
  540.     /* Construct the initial heap, with least frequent element in
  541.      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  542.      * heap[0] is not used.
  543.      */
  544.     s->heap_len = 0, s->heap_max = HEAP_SIZE;
  545.  
  546.     for (n = 0; n < elems; n++) {
  547.         if (tree[n].Freq != 0) {
  548.             s->heap[++(s->heap_len)] = max_code = n;
  549.             s->depth[n] = 0;
  550.         } else {
  551.             tree[n].Len = 0;
  552.         }
  553.     }
  554.  
  555.     /* The pkzip format requires that at least one distance code exists,
  556.      * and that at least one bit should be sent even if there is only one
  557.      * possible code. So to avoid special checks later on we force at least
  558.      * two codes of non zero frequency.
  559.      */
  560.     while (s->heap_len < 2) {
  561.         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  562.         tree[node].Freq = 1;
  563.         s->depth[node] = 0;
  564.         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  565.         /* node is 0 or 1 so it does not have extra bits */
  566.     }
  567.     desc->max_code = max_code;
  568.  
  569.     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  570.      * establish sub-heaps of increasing lengths:
  571.      */
  572.     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  573.  
  574.     /* Construct the Huffman tree by repeatedly combining the least two
  575.      * frequent nodes.
  576.      */
  577.     node = elems;              /* next internal node of the tree */
  578.     do {
  579.         pqremove(s, tree, n);  /* n = node of least frequency */
  580.         m = s->heap[SMALLEST]; /* m = node of next least frequency */
  581.  
  582.         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  583.         s->heap[--(s->heap_max)] = m;
  584.  
  585.         /* Create a new node father of n and m */
  586.         tree[node].Freq = tree[n].Freq + tree[m].Freq;
  587.         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
  588.         tree[n].Dad = tree[m].Dad = (ush)node;
  589. #ifdef DUMP_BL_TREE
  590.         if (tree == s->bl_tree) {
  591.             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  592.                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  593.         }
  594. #endif
  595.         /* and insert the new node in the heap */
  596.         s->heap[SMALLEST] = node++;
  597.         pqdownheap(s, tree, SMALLEST);
  598.  
  599.     } while (s->heap_len >= 2);
  600.  
  601.     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  602.  
  603.     /* At this point, the fields freq and dad are set. We can now
  604.      * generate the bit lengths.
  605.      */
  606.     gen_bitlen(s, (tree_desc *)desc);
  607.  
  608.     /* The field len is now set, we can generate the bit codes */
  609.     gen_codes ((ct_data *)tree, max_code, s->bl_count);
  610. }
  611.  
  612. /* ===========================================================================
  613.  * Scan a literal or distance tree to determine the frequencies of the codes
  614.  * in the bit length tree.
  615.  */
  616. local void scan_tree (deflate_state *s, ct_data *tree, int max_code)
  617. {
  618.     int n;                     /* iterates over all tree elements */
  619.     int prevlen = -1;          /* last emitted length */
  620.     int curlen;                /* length of current code */
  621.     int nextlen = tree[0].Len; /* length of next code */
  622.     int count = 0;             /* repeat count of the current code */
  623.     int max_count = 7;         /* max repeat count */
  624.     int min_count = 4;         /* min repeat count */
  625.  
  626.     if (nextlen == 0) max_count = 138, min_count = 3;
  627.     tree[max_code+1].Len = (ush)0xffff; /* guard */
  628.  
  629.     for (n = 0; n <= max_code; n++) {
  630.         curlen = nextlen; nextlen = tree[n+1].Len;
  631.         if (++count < max_count && curlen == nextlen) {
  632.             continue;
  633.         } else if (count < min_count) {
  634.             s->bl_tree[curlen].Freq += count;
  635.         } else if (curlen != 0) {
  636.             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  637.             s->bl_tree[REP_3_6].Freq++;
  638.         } else if (count <= 10) {
  639.             s->bl_tree[REPZ_3_10].Freq++;
  640.         } else {
  641.             s->bl_tree[REPZ_11_138].Freq++;
  642.         }
  643.         count = 0; prevlen = curlen;
  644.         if (nextlen == 0) {
  645.             max_count = 138, min_count = 3;
  646.         } else if (curlen == nextlen) {
  647.             max_count = 6, min_count = 3;
  648.         } else {
  649.             max_count = 7, min_count = 4;
  650.         }
  651.     }
  652. }
  653.  
  654. /* ===========================================================================
  655.  * Send a literal or distance tree in compressed form, using the codes in
  656.  * bl_tree.
  657.  */
  658. local void send_tree (deflate_state *s, ct_data *tree, int max_code)
  659. {
  660.     int n;                     /* iterates over all tree elements */
  661.     int prevlen = -1;          /* last emitted length */
  662.     int curlen;                /* length of current code */
  663.     int nextlen = tree[0].Len; /* length of next code */
  664.     int count = 0;             /* repeat count of the current code */
  665.     int max_count = 7;         /* max repeat count */
  666.     int min_count = 4;         /* min repeat count */
  667.  
  668.     /* tree[max_code+1].Len = -1; */  /* guard already set */
  669.     if (nextlen == 0) max_count = 138, min_count = 3;
  670.  
  671.     for (n = 0; n <= max_code; n++) {
  672.         curlen = nextlen; nextlen = tree[n+1].Len;
  673.         if (++count < max_count && curlen == nextlen) {
  674.             continue;
  675.         } else if (count < min_count) {
  676.             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  677.  
  678.         } else if (curlen != 0) {
  679.             if (curlen != prevlen) {
  680.                 send_code(s, curlen, s->bl_tree); count--;
  681.             }
  682.             Assert(count >= 3 && count <= 6, " 3_6?");
  683.             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  684.  
  685.         } else if (count <= 10) {
  686.             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  687.  
  688.         } else {
  689.             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  690.         }
  691.         count = 0; prevlen = curlen;
  692.         if (nextlen == 0) {
  693.             max_count = 138, min_count = 3;
  694.         } else if (curlen == nextlen) {
  695.             max_count = 6, min_count = 3;
  696.         } else {
  697.             max_count = 7, min_count = 4;
  698.         }
  699.     }
  700. }
  701.  
  702. /* ===========================================================================
  703.  * Construct the Huffman tree for the bit lengths and return the index in
  704.  * bl_order of the last bit length code to send.
  705.  */
  706. local int build_bl_tree(deflate_state *s)
  707. {
  708.     int max_blindex;  /* index of last bit length code of non zero freq */
  709.  
  710.     /* Determine the bit length frequencies for literal and distance trees */
  711.     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  712.     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  713.  
  714.     /* Build the bit length tree: */
  715.     build_tree(s, (tree_desc *)(&(s->bl_desc)));
  716.     /* opt_len now includes the length of the tree representations, except
  717.      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  718.      */
  719.  
  720.     /* Determine the number of bit length codes to send. The pkzip format
  721.      * requires that at least 4 bit length codes be sent. (appnote.txt says
  722.      * 3 but the actual value used is 4.)
  723.      */
  724.     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  725.         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  726.     }
  727.     /* Update opt_len to include the bit length tree and counts */
  728.     s->opt_len += 3*(max_blindex+1) + 5+5+4;
  729.     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  730.             s->opt_len, s->static_len));
  731.  
  732.     return max_blindex;
  733. }
  734.  
  735. /* ===========================================================================
  736.  * Send the header for a block using dynamic Huffman trees: the counts, the
  737.  * lengths of the bit length codes, the literal tree and the distance tree.
  738.  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  739.  */
  740. local void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes)
  741. {
  742.     int rank;                    /* index in bl_order */
  743.  
  744.     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  745.     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  746.             "too many codes");
  747.     Tracev((stderr, "\nbl counts: "));
  748.     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  749.     send_bits(s, dcodes-1,   5);
  750.     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
  751.     for (rank = 0; rank < blcodes; rank++) {
  752.         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  753.         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  754.     }
  755.     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  756.  
  757.     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  758.     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  759.  
  760.     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  761.     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  762. }
  763.  
  764. /* ===========================================================================
  765.  * Send a stored block
  766.  */
  767. void _tr_stored_block(deflate_state *s, charf *buf, ulg stored_len, int eof)
  768. {
  769.     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
  770.     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  771.     s->compressed_len += (stored_len + 4) << 3;
  772.  
  773.     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  774. }
  775.  
  776. /* ===========================================================================
  777.  * Send one empty static block to give enough lookahead for inflate.
  778.  * This takes 10 bits, of which 7 may remain in the bit buffer.
  779.  * The current inflate code requires 9 bits of lookahead. If the
  780.  * last two codes for the previous block (real code plus EOB) were coded
  781.  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  782.  * the last real code. In this case we send two empty static blocks instead
  783.  * of one. (There are no problems if the previous block is stored or fixed.)
  784.  * To simplify the code, we assume the worst case of last real code encoded
  785.  * on one bit only.
  786.  */
  787. void _tr_align(deflate_state *s)
  788. {
  789.     send_bits(s, STATIC_TREES<<1, 3);
  790.     send_code(s, END_BLOCK, static_ltree);
  791.     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  792.     bi_flush(s);
  793.     /* Of the 10 bits for the empty block, we have already sent
  794.      * (10 - bi_valid) bits. The lookahead for the last real code (before
  795.      * the EOB of the previous block) was thus at least one plus the length
  796.      * of the EOB plus what we have just sent of the empty static block.
  797.      */
  798.     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  799.         send_bits(s, STATIC_TREES<<1, 3);
  800.         send_code(s, END_BLOCK, static_ltree);
  801.         s->compressed_len += 10L;
  802.         bi_flush(s);
  803.     }
  804.     s->last_eob_len = 7;
  805. }
  806.  
  807. /* ===========================================================================
  808.  * Determine the best encoding for the current block: dynamic trees, static
  809.  * trees or store, and output the encoded block to the zip file. This function
  810.  * returns the total compressed length for the file so far.
  811.  */
  812. ulg _tr_flush_block(deflate_state *s, charf *buf, ulg stored_len, int eof)
  813. {
  814.     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  815.     int max_blindex = 0;  /* index of last bit length code of non zero freq */
  816.  
  817.     /* Build the Huffman trees unless a stored block is forced */
  818.     if (s->level > 0) {
  819.  
  820.          /* Check if the file is ascii or binary */
  821.         if (s->data_type == Z_UNKNOWN) set_data_type(s);
  822.  
  823.         /* Construct the literal and distance trees */
  824.         build_tree(s, (tree_desc *)(&(s->l_desc)));
  825.         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  826.                 s->static_len));
  827.  
  828.         build_tree(s, (tree_desc *)(&(s->d_desc)));
  829.         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  830.                 s->static_len));
  831.         /* At this point, opt_len and static_len are the total bit lengths of
  832.          * the compressed block data, excluding the tree representations.
  833.          */
  834.  
  835.         /* Build the bit length tree for the above two trees, and get the index
  836.          * in bl_order of the last bit length code to send.
  837.          */
  838.         max_blindex = build_bl_tree(s);
  839.  
  840.         /* Determine the best encoding. Compute first the block length in bytes*/
  841.         opt_lenb = (s->opt_len+3+7)>>3;
  842.         static_lenb = (s->static_len+3+7)>>3;
  843.  
  844.         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  845.                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  846.                 s->last_lit));
  847.  
  848.         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  849.  
  850.     } else {
  851.         Assert(buf != (char*)0, "lost buf");
  852.         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  853.     }
  854.  
  855.     /* If compression failed and this is the first and last block,
  856.      * and if the .zip file can be seeked (to rewrite the local header),
  857.      * the whole file is transformed into a stored file:
  858.      */
  859. #ifdef STORED_FILE_OK
  860. #  ifdef FORCE_STORED_FILE
  861.     if (eof && s->compressed_len == 0L) { /* force stored file */
  862. #  else
  863.     if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) {
  864. #  endif
  865.         /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  866.         if (buf == (charf*)0) error ("block vanished");
  867.  
  868.         copy_block(buf, (unsigned)stored_len, 0); /* without header */
  869.         s->compressed_len = stored_len << 3;
  870.         s->method = STORED;
  871.     } else
  872. #endif /* STORED_FILE_OK */
  873.  
  874. #ifdef FORCE_STORED
  875.     if (buf != (char*)0) { /* force stored block */
  876. #else
  877.     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  878.                        /* 4: two words for the lengths */
  879. #endif
  880.         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  881.          * Otherwise we can't have processed more than WSIZE input bytes since
  882.          * the last block flush, because compression would have been
  883.          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  884.          * transform a block into a stored block.
  885.          */
  886.         _tr_stored_block(s, buf, stored_len, eof);
  887.  
  888. #ifdef FORCE_STATIC
  889.     } else if (static_lenb >= 0) { /* force static trees */
  890. #else
  891.     } else if (static_lenb == opt_lenb) {
  892. #endif
  893.         send_bits(s, (STATIC_TREES<<1)+eof, 3);
  894.         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  895.         s->compressed_len += 3 + s->static_len;
  896.     } else {
  897.         send_bits(s, (DYN_TREES<<1)+eof, 3);
  898.         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  899.                        max_blindex+1);
  900.         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  901.         s->compressed_len += 3 + s->opt_len;
  902.     }
  903.     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  904.     init_block(s);
  905.  
  906.     if (eof) {
  907.         bi_windup(s);
  908.         s->compressed_len += 7;  /* align on byte boundary */
  909.     }
  910.     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  911.            s->compressed_len-7*eof));
  912.  
  913.     return s->compressed_len >> 3;
  914. }
  915.  
  916. /* ===========================================================================
  917.  * Save the match info and tally the frequency counts. Return true if
  918.  * the current block must be flushed.
  919.  */
  920. int _tr_tally (deflate_state *s, unsigned dist, unsigned lc)
  921. {
  922.     s->d_buf[s->last_lit] = (ush)dist;
  923.     s->l_buf[s->last_lit++] = (uch)lc;
  924.     if (dist == 0) {
  925.         /* lc is the unmatched char */
  926.         s->dyn_ltree[lc].Freq++;
  927.     } else {
  928.         s->matches++;
  929.         /* Here, lc is the match length - MIN_MATCH */
  930.         dist--;             /* dist = match distance - 1 */
  931.         Assert((ush)dist < (ush)MAX_DIST(s) &&
  932.                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  933.                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
  934.  
  935.         s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  936.         s->dyn_dtree[d_code(dist)].Freq++;
  937.     }
  938.  
  939.     /* Try to guess if it is profitable to stop the current block here */
  940.     if (s->level > 2 && (s->last_lit & 0xfff) == 0) {
  941.         /* Compute an upper bound for the compressed length */
  942.         ulg out_length = (ulg)s->last_lit*8L;
  943.         ulg in_length = (ulg)((long)s->strstart - s->block_start);
  944.         int dcode;
  945.         for (dcode = 0; dcode < D_CODES; dcode++) {
  946.             out_length += (ulg)s->dyn_dtree[dcode].Freq *
  947.                 (5L+extra_dbits[dcode]);
  948.         }
  949.         out_length >>= 3;
  950.         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  951.                s->last_lit, in_length, out_length,
  952.                100L - out_length*100L/in_length));
  953.         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  954.     }
  955.     return (s->last_lit == s->lit_bufsize-1);
  956.     /* We avoid equality with lit_bufsize because of wraparound at 64K
  957.      * on 16 bit machines and because stored blocks are restricted to
  958.      * 64K-1 bytes.
  959.      */
  960. }
  961.  
  962. /* ===========================================================================
  963.  * Send the block data compressed using the given Huffman trees
  964.  */
  965. local void compress_block(deflate_state *s, ct_data *ltree, ct_data *dtree)
  966. {
  967.     unsigned dist;      /* distance of matched string */
  968.     int lc;             /* match length or unmatched char (if dist == 0) */
  969.     unsigned lx = 0;    /* running index in l_buf */
  970.     unsigned code;      /* the code to send */
  971.     int extra;          /* number of extra bits to send */
  972.  
  973.     if (s->last_lit != 0) do {
  974.         dist = s->d_buf[lx];
  975.         lc = s->l_buf[lx++];
  976.         if (dist == 0) {
  977.             send_code(s, lc, ltree); /* send a literal byte */
  978.             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  979.         } else {
  980.             /* Here, lc is the match length - MIN_MATCH */
  981.             code = length_code[lc];
  982.             send_code(s, code+LITERALS+1, ltree); /* send the length code */
  983.             extra = extra_lbits[code];
  984.             if (extra != 0) {
  985.                 lc -= base_length[code];
  986.                 send_bits(s, lc, extra);       /* send the extra length bits */
  987.             }
  988.             dist--; /* dist is now the match distance - 1 */
  989.             code = d_code(dist);
  990.             Assert (code < D_CODES, "bad d_code");
  991.  
  992.             send_code(s, code, dtree);       /* send the distance code */
  993.             extra = extra_dbits[code];
  994.             if (extra != 0) {
  995.                 dist -= base_dist[code];
  996.                 send_bits(s, dist, extra);   /* send the extra distance bits */
  997.             }
  998.         } /* literal or match pair ? */
  999.  
  1000.         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  1001.         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
  1002.  
  1003.     } while (lx < s->last_lit);
  1004.  
  1005.     send_code(s, END_BLOCK, ltree);
  1006.     s->last_eob_len = ltree[END_BLOCK].Len;
  1007. }
  1008.  
  1009. /* ===========================================================================
  1010.  * Set the data type to ASCII or BINARY, using a crude approximation:
  1011.  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  1012.  * IN assertion: the fields freq of dyn_ltree are set and the total of all
  1013.  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  1014.  */
  1015. local void set_data_type(deflate_state *s)
  1016. {
  1017.     int n = 0;
  1018.     unsigned ascii_freq = 0;
  1019.     unsigned bin_freq = 0;
  1020.     while (n < 7)        bin_freq += s->dyn_ltree[n++].Freq;
  1021.     while (n < 128)    ascii_freq += s->dyn_ltree[n++].Freq;
  1022.     while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
  1023.     s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
  1024. }
  1025.  
  1026. /* ===========================================================================
  1027.  * Reverse the first len bits of a code, using straightforward code (a faster
  1028.  * method would use a table)
  1029.  * IN assertion: 1 <= len <= 15
  1030.  */
  1031. local unsigned bi_reverse(unsigned code, int len)
  1032. {
  1033.     register unsigned res = 0;
  1034.     do {
  1035.         res |= code & 1;
  1036.         code >>= 1, res <<= 1;
  1037.     } while (--len > 0);
  1038.     return res >> 1;
  1039. }
  1040.  
  1041. /* ===========================================================================
  1042.  * Flush the bit buffer, keeping at most 7 bits in it.
  1043.  */
  1044. local void bi_flush(deflate_state *s)
  1045. {
  1046.     if (s->bi_valid == 16) {
  1047.         put_short(s, s->bi_buf);
  1048.         s->bi_buf = 0;
  1049.         s->bi_valid = 0;
  1050.     } else if (s->bi_valid >= 8) {
  1051.         put_byte(s, (Byte)s->bi_buf);
  1052.         s->bi_buf >>= 8;
  1053.         s->bi_valid -= 8;
  1054.     }
  1055. }
  1056.  
  1057. /* ===========================================================================
  1058.  * Flush the bit buffer and align the output on a byte boundary
  1059.  */
  1060. local void bi_windup(deflate_state *s)
  1061. {
  1062.     if (s->bi_valid > 8) {
  1063.         put_short(s, s->bi_buf);
  1064.     } else if (s->bi_valid > 0) {
  1065.         put_byte(s, (Byte)s->bi_buf);
  1066.     }
  1067.     s->bi_buf = 0;
  1068.     s->bi_valid = 0;
  1069. #ifdef DEBUG
  1070.     s->bits_sent = (s->bits_sent+7) & ~7;
  1071. #endif
  1072. }
  1073.  
  1074. /* ===========================================================================
  1075.  * Copy a stored block, storing first the length and its
  1076.  * one's complement if requested.
  1077.  */
  1078. local void copy_block(deflate_state *s, charf *buf, unsigned len, int header)
  1079. {
  1080.     bi_windup(s);        /* align on byte boundary */
  1081.     s->last_eob_len = 8; /* enough lookahead for inflate */
  1082.  
  1083.     if (header) {
  1084.         put_short(s, (ush)len);   
  1085.         put_short(s, (ush)~len);
  1086. #ifdef DEBUG
  1087.         s->bits_sent += 2*16;
  1088. #endif
  1089.     }
  1090. #ifdef DEBUG
  1091.     s->bits_sent += (ulg)len<<3;
  1092. #endif
  1093.     while (len--) {
  1094.         put_byte(s, *buf++);
  1095.     }
  1096. }
  1097.